package shangji;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;

public class Shangji_2 {
    public static void main(String[] args) throws Exception{
        //得到DOM解析器的工厂实例
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        //从DOM工厂获得DOM解析器
        DocumentBuilder db = dbf.newDocumentBuilder();
        //解析XML文档,得到一个Document对象,即DOM树
        Document doc = db.parse("src/收藏信息.xml");
        //创建brand节点
        Element brand = doc.createElement("Brand");
        brand.setAttribute("name","三星");
        //创建Type节点
        Element typeElement = doc.createElement("Type");
        typeElement.setAttribute("name","NoteX");
        //添加父子关系
        brand.appendChild(typeElement);
        Element phone = (Element) doc.getElementsByTagName("PhoneInfo").item(0);
        phone.appendChild(brand);
        //修改
        NodeList list = doc.getElementsByTagName("Brand");
        for (int i=0;i<list.getLength();i++){
            brand= (Element) list.item(i);
            String brandName = brand.getAttribute("name");
            if (brandName.equals("三星")){
                brand.setAttribute("name","SAMSUNG");
            }
        }
        //删除
        for (int j =0;j<list.getLength();j++){
            brand = (Element) list.item(j);
            String BrandName = brand.getAttribute("name");
            if (BrandName.equals("SAMSUNG")){
                brand.getParentNode().removeChild(brand);
            }
        }
        //保存
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource domSource = new DOMSource();
        //设置编码类型
        transformer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
        StreamResult result = new StreamResult(new FileOutputStream("src/上机2.xml"));
        //把DOM树转换为XML文件
        transformer.transform(domSource,result);
    }
}
